package zzy.fast.http;


import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/***
 *
 * 功能描述: 网络请求
 *
 * @author zzy
 *
 *  2019-10-25 14:56
 *
 ***/
public class OkHttp {

    private ResultCallback mResultCallback;

    private static OkHttp mOkHttp;

    private OkHttpClient mOkHttpClient;

    private OkHttp() {
        mOkHttpClient = new OkHttpClient();
    }

    public static OkHttp getInstance() {
        if (mOkHttp == null) {
            synchronized (OkHttp.class) {
                if (mOkHttp == null) {
                    mOkHttp = new OkHttp();
                }
            }
        }
        return mOkHttp;
    }


    public OkHttp get(String urlStr) {
        final Request request = new Request.Builder().url(urlStr).build();
        mOkHttpClient.newCall(request).enqueue(mCallback);
        return this;
    }


    public OkHttp post(String urlStr, String jsonBody) {
        RequestBody requestBody = RequestBody.create(jsonBody, MediaType.get("json"));
        Request request = new Request.Builder().url(urlStr).post(requestBody).build();
        mOkHttpClient.newCall(request).enqueue(mCallback);
        return this;
    }


    private Callback mCallback = new Callback() {
        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e) {
            mResultCallback.fail(e.getMessage());
        }

        @Override
        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
            if (response.isSuccessful()) {
                mResultCallback.success(response.body().string());
            } else {
                mResultCallback.fail(response.message());
            }
        }
    };

    public void setResultCallback(ResultCallback callback) {
        mResultCallback = callback;
    }

    public static interface ResultCallback {

        void success(String result);

        void fail(String msg);

    }
}
